package com.xh.bussiness.tms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xh.bussiness.classinteractive.service.IClassInteractiveStudentCommonService;
import com.xh.bussiness.system.bean.dto.StudentDto;
import com.xh.bussiness.system.model.Student;
import com.xh.bussiness.system.service.IStudentService;
import com.xh.bussiness.tms.bean.dto.StudentAttendBean;
import com.xh.bussiness.tms.bean.dto.StudentAttendStatusBean;
import com.xh.bussiness.tms.bean.request.SaveOrUpdateStudentAttendRequest;
import com.xh.bussiness.tms.bean.request.StudentAttendStatusRequest;
import com.xh.bussiness.tms.dao.StudentAttendMapper;
import com.xh.bussiness.tms.model.Class;
import com.xh.bussiness.tms.model.StudentAttend;
import com.xh.bussiness.tms.service.IClassManageService;
import com.xh.bussiness.tms.service.IStudentAttendService;
import com.xh.core.bean.XhPage;
import com.xh.core.service.impl.BaseServiceImpl;
import com.xh.core.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Pitt Cheung
 * @date 2021/7/12 14:28
 */
@Service
public class StudentAttendServiceImpl extends BaseServiceImpl<StudentAttendMapper, StudentAttend> implements IStudentAttendService {

    @Autowired
    private IClassManageService classManageService;
    @Autowired
    private IStudentService studentService;
    @Autowired
    private IClassInteractiveStudentCommonService classInteractiveStudentCommonService;

    @Override
    public String batchSaveOrUpdateStudentAttend(SaveOrUpdateStudentAttendRequest request) {
        if (request.getStudentAttends().isEmpty()) {
            return "学生考勤数据不能为空";
        }
        if (StringUtils.isEmpty(request.getClassId())) {
            return "班级id不能为空";
        }
        if (StringUtils.isEmpty(request.getCurrId())) {
            return "班级课次id";
        }
        if (request.getCurrDate() == null) {
            return "上课日期不能为空";
        }
        for (StudentAttendStatusRequest studentAttend : request.getStudentAttends()) {
            if (StringUtils.isEmpty(studentAttend.getStudentAttendId())) {
                Student stu = studentService.getById(studentAttend.getStudentId());
                if (StringUtils.isEmpty(stu.getHead())) {
                    stu.setHead(studentAttend.getStudentHeadUrl());
                    studentService.update(stu);
                }

                StudentAttend attend = StudentAttend.builder()
                        .classId(request.getClassId())
                        .currId(request.getCurrId())
                        .currDate(request.getCurrDate())
                        .currOrderNo(request.getCurrOrderNo())
                        .status(studentAttend.getStatus())
                        .studentId(studentAttend.getStudentId())
                        .studentName(studentAttend.getStudentName())
                        .build();
                this.insert(attend);
            }else{
                StudentAttend oldAttend = this.getById(studentAttend.getStudentAttendId());
                if (oldAttend != null) {
                    oldAttend.setStatus(studentAttend.getStatus());
                    this.update(oldAttend);
                }
            }
        }
        return  null;
    }

    @Override
    public StudentAttendBean queryStudentAttendData(String classId, String currId) {
        Class aClass = classManageService.getById(classId, Class.class);
        if (aClass == null) {
            return new StudentAttendBean();
        }
        StudentAttendBean bean = new StudentAttendBean();
        bean.setClassId(aClass.getId());
        bean.setClassName(aClass.getTitle());
        //状态（1:出勤；2：迟到；3：缺勤；4：请假）
        long attendanceCount = 0;
        long lateCount = 0;
        long noAttendanceCount =0;
        long leaveCount = 0;

        QueryWrapper qw = new QueryWrapper();
        qw.eq("class_id", classId);
        qw.eq("curr_id", currId);
        List<StudentAttend> list = this.dao.selectList(qw);
        List<StudentAttendStatusBean> studentAttendStatusBeans = new ArrayList<>();
        if (CollectionUtils.isEmpty(list)) {
            XhPage page = new XhPage();
            page.setCurrent(1);
            page.setSize(100);
            XhPage<StudentDto> pageResult = classManageService.queryStudentsByClassId(page, StringUtils.isEmpty(aClass.getThirdId()) ? aClass.getId() : aClass.getThirdId(), null);
            if (!CollectionUtils.isEmpty(pageResult.getRecords())) {
                 List<StudentDto> studentDtos = pageResult.getRecords();
                for (StudentDto record :studentDtos) {
                    StudentAttendStatusBean studentAttend = new StudentAttendStatusBean();
                    studentAttend.setStatus(1);
                    studentAttend.setStudentName(record.getName());
                    studentAttend.setStudentHeadUrl(record.getHead());
                    studentAttend.setStudentId(record.getId());
                    studentAttend.setScore(0);
                    studentAttendStatusBeans.add(studentAttend);
                }
            }
        }else{
            attendanceCount = list.stream().filter(item -> item.getStatus().equals(1)).count();
            lateCount = list.stream().filter(item -> item.getStatus().equals(2)).count();
            noAttendanceCount = list.stream().filter(item -> item.getStatus().equals(3)).count();
            leaveCount = list.stream().filter(item -> item.getStatus().equals(4)).count();

            for (StudentAttend attend : list) {
                Student student = studentService.getById(attend.getStudentId());

                StudentAttendStatusBean bean1 = new StudentAttendStatusBean();
                bean1.setStudentId(attend.getStudentId());
                bean1.setStudentName(attend.getStudentName());
                bean1.setStatus(attend.getStatus());
                if (student != null) {
                    bean1.setStudentHeadUrl(student.getHead());
                }
                bean1.setStudentAttendId(attend.getId());
                Integer totalScore = classInteractiveStudentCommonService.queryStudentTotalScore(attend.getId());
                bean1.setScore(totalScore == null ? 0 : totalScore);

                studentAttendStatusBeans.add(bean1);
            }
        }
        bean.setAttendanceCount(attendanceCount);
        bean.setLateCount(lateCount);
        bean.setNoAttendanceCount(noAttendanceCount);
        bean.setLeaveCount(leaveCount);
        bean.setStudentAttendStatusBeans(studentAttendStatusBeans);

        return bean;
    }

    @Override
    public List<String> queryCurrId(String classId) {
        return this.dao.queryCurrId(classId);
    }
}
